package com.jie.other.jetpack.flow

import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.jie.commonlib.base.BaseActivity
import com.jie.other.R
import com.jie.other.databinding.OtherActivityFlowTestBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * 用于测试验证flow的基本使用
 * 参考资料：https://mp.weixin.qq.com/s/TRr_isgU7VVVuJ9rOMZUhw
 */
class FlowTestActivity : BaseActivity() {

    private lateinit var mViewBinding : OtherActivityFlowTestBinding
    private val mMainViewModel by viewModels<MainViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding = OtherActivityFlowTestBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)

        initActionBar()
        initView()
    }

    private fun initActionBar() {
        supportActionBar?.apply {
            setDisplayHomeAsUpEnabled(true)
            setTitle(R.string.other_flow)
        }
    }

    private fun initView() {
        mViewBinding.btnStart.setOnClickListener {
            lifecycleScope.launch {
                // collectLatest函数只接收处理最新的数据
                // 如果有新数据到来了而前一个数据还没有处理完，则会将前一个数据剩余的处理逻辑全部取消
                mMainViewModel.timFlow.collectLatest { time ->
                    mViewBinding.tvTime.text = time.toString()
                    delay(3000)
                    // FIXME: 使用 collectLatest 下面这句代码将不会执行
                    LogUtils.i("这是测试...$time")
                }
            }
        }
    }

}